package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.api.ProductApi;
import com.cskaoyan.order.biz.TransOutboundInvoker;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.factory.OrderProcessPipelineFactory;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.OrderDetail;
import com.cskaoyan.order.service.OrderCoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class OrderCoreServiceImpl implements OrderCoreService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderItemMapper orderItemMapper;

    @Autowired
    OrderShippingMapper orderShippingMapper;

    @Autowired
    OrderProcessPipelineFactory orderProcessPipelineFactory;

    @Autowired
    StockMapper stockMapper;

    @Autowired
    OrderConverter orderConverter;

    @Autowired
    ProductApi productApi;


    /**
     * 创建订单的处理流程
     *
     * @param request
     * @return
     */
    @Override
    public CreateOrderResponse createOrder(CreateOrderRequest request) {
        CreateOrderResponse response = new CreateOrderResponse();
        try {
            //创建pipeline对象
            TransOutboundInvoker invoker = orderProcessPipelineFactory.build(request);

            //启动pipeline
            invoker.start(); //启动流程（pipeline来处理）

            //获取处理结果
            AbsTransHandlerContext context = invoker.getContext();

            //把处理结果转换为response
            response = (CreateOrderResponse) context.getConvert().convertCtx2Respond(context);

        } catch (Exception e) {
            log.error("OrderCoreServiceImpl.createOrder Occur Exception :" + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    @Override
    public CancelOrderResponse cancelOrder(CancelOrderRequest request) {

        String orderId = request.getOrderId();
        CancelOrderResponse cancelOrderResponse = new CancelOrderResponse();

        try {

            //更改订单表状态为ORDER_STATUS_TRANSACTION_CANCEL （7）
            Order order = new Order();
            order.setOrderId(orderId);
            order.setStatus(OrderConstants.ORDER_STATUS_TRANSACTION_CANCEL);
            int i = orderMapper.updateByPrimaryKeySelective(order);
            if(i != 1){
                throw new Exception();
            }
            cancelOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
            cancelOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(cancelOrderResponse,e);
        }
        return cancelOrderResponse;
    }


    @Override
    public DeleteOrderResponse deleteOrder(DeleteOrderRequest request) {
        //1.删除订单表数据2.删除关联表数据3.删除邮寄表数据4.恢复库存
        String orderId = request.getOrderId();
        DeleteOrderResponse deleteOrderResponse = new DeleteOrderResponse();

        try {
            //删除订单表数据
            int i = orderMapper.deleteByPrimaryKey(orderId);
            //获取订单的商品id
            //删除关联表数据
            Example example = new Example(OrderItem.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("orderId", orderId);
            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            int j = orderItemMapper.deleteByExample(example);
            //恢复库存
            for (OrderItem orderItem : orderItems) {
                //修改库存表
                Long itemId = orderItem.getItemId();
                //主键语句有问题
                Stock stock = stockMapper.selectStockForUpdate(itemId);
                Integer newLockCount = stock.getLockCount() - 1;
                stock.setLockCount(newLockCount);
                Long newStockCount = stock.getStockCount() + 1;
                stock.setStockCount(newStockCount);

                Example example2 = new Example(Stock.class);
                example2.createCriteria().andEqualTo("itemId",itemId);
                //主键语句有问题
                stockMapper.updateByExampleSelective(stock,example2);
                //修改商品表数量 TODO
                Boolean updated = productApi.updateItemNum(itemId, newStockCount);
                if(!updated){
                    throw new Exception("调用商品服务异常");
                }
            }
            //删除邮寄表数据
            int k = orderShippingMapper.deleteByPrimaryKey(orderId);
            if (!(i == 1 && j > 0 && k == 1)) {
                throw new Exception("删除异常");
            }
            deleteOrderResponse.setCode(OrderRetCode.SUCCESS.getCode());
            deleteOrderResponse.setMsg(OrderRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(deleteOrderResponse, e);
        }
        return deleteOrderResponse;
    }

    /**
     * lxc
     * 查询当前用户所有订单
     * @param orderListRequest
     * @return
     */
    @Override
    public OrderListResponse queryAllOrders(OrderListRequest orderListRequest) {

        OrderListResponse orderListResponse = new OrderListResponse();

        try {
            orderListRequest.requestCheck();
            Long userId = orderListRequest.getUserId();
            Example example = new Example(Order.class);
            Example.Criteria criteria = example.createCriteria();

            criteria.andEqualTo("userId",userId);

            // 查询订单的总数
            int orderCount = orderMapper.selectCountByExample(example);

            List<OrderDetailInfo> detailInfoList = new ArrayList<>();

            List<Order> orders = orderMapper.selectByExample(example);
            for (Order order : orders) {
                OrderDetailInfo orderDetailInfo = orderConverter.order2detail(order);
                // 通过orderId查出orderItem中该订单号的所有信息
                List<OrderItem> orderItems = orderItemMapper.queryByOrderId(order.getOrderId());
                List<OrderItemDto> orderItemDto = orderConverter.item2dto(orderItems);
                // 通过orderId查出orderShipping中该订单号的所有信息
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());
                OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
                orderDetailInfo.setOrderItemDto(orderItemDto);
                orderDetailInfo.setOrderShippingDto(orderShippingDto);
                detailInfoList.add(orderDetailInfo);
            }
            Integer page = orderListRequest.getPage();
            Integer size = orderListRequest.getSize();
            List<OrderDetailInfo> ordersByPage;
            if ((page * size) > detailInfoList.size()) {
                ordersByPage = detailInfoList.subList((page - 1) * size,orders.size());
            } else {
                ordersByPage = detailInfoList.subList((page - 1) * size, page * size);
            }
            orderListResponse.setDetailInfoList(ordersByPage);
            orderListResponse.setTotal((long) orderCount);
            orderListResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            orderListResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(orderListResponse,e);
        }

        return orderListResponse;
    }

    /**
     * lxc
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderDetail queryOrderDetail(Long id,String username,Long uid) {

        OrderDetail orderDetail = new OrderDetail();

        // 根据订单id查出该订单
        Order order = orderMapper.selectByPrimaryKey(id);
        // 根据订单id查出该订单对应的收货信息
        OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(id);

        orderDetail.setUserName(orderShipping.getReceiverName());
        orderDetail.setOrderTotal(order.getPayment());
        orderDetail.setUserId(uid);
        orderDetail.setTel(orderShipping.getReceiverPhone());
        orderDetail.setStreetName(orderShipping.getReceiverAddress());
        orderDetail.setOrderStatus(order.getStatus());

        List<OrderItem> orderItems = orderItemMapper.queryByOrderId(id.toString());
        List<OrderItemDto> orderItemDtos = orderConverter.item2dto(orderItems);

        orderDetail.setGoodsList(orderItemDtos);

        return orderDetail;
    }

}
